package com.landleaf.smarthome.net.mqtt;

import com.landleaf.smarthome.net.mqtt.bean.MqttMsgBodyModel;
import com.landleaf.smarthome.util.JsonUtils;
import com.landleaf.smarthome.util.LogUtils;
import com.landleaf.smarthome.util.rxutils.RxJavaUtils;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import io.reactivex.schedulers.Schedulers;

/**
 * When I wrote this, only God and I understood what I was doing
 * Now, God only knows
 * Created by 海航
 * 2020/9/25
 * 功能描述:
 */
public class MqttMessageCallback implements MqttCallback {
    MqttMsgHandler mMsgHandler;


    //连接丢失后，一般在这里面进行重连
    @Override
    public void connectionLost(Throwable cause) {
        LogUtils.d("connectionLost-->" + cause.getMessage());
    }

    //publish后会执行到这里
    //subscribe后得到的消息会执行到这里面
    @Override
    public void messageArrived(String topic, MqttMessage message) {
        LogUtils.d("消息接受成功-->"+new String(message.getPayload()));
        RxJavaUtils.createObservable(message).filter(s -> MqttConst.COMMON_RESPONSE_TOPIC.equals(topic))
                .observeOn(Schedulers.io())
                .map(msg -> {
                    MqttMsgBodyModel msgBodyModel = null;
                    msgBodyModel = JsonUtils.jsonToObj(new String(msg.getPayload()), MqttMsgBodyModel.class);
                    return msgBodyModel;
                })
                .subscribe(data -> {
                    switch (data.getHeader().getName()) {
                        case MqttConst.METHOD_DEVICE_WRITE:
                            mMsgHandler.handlerDeviceWriteMsg(data);
                            break;
                        case MqttConst.METHOD_DEVICE_READ:
                            mMsgHandler.handlerDeviceReadMsg(data);
                            break;
                        case MqttConst.METHOD_SCENE_SET:
                            mMsgHandler.handlerSceneSetMsg(data);
                            break;
                        case MqttConst.METHOD_CONFIG_UPDATE:
                            mMsgHandler.handlerConfigUpdateMsg(data);
                            break;
                        case MqttConst.METHOD_DEVICE_UPDATE:
                            mMsgHandler.handlerDeviceUpdateMsg(data);
                            break;
                        case MqttConst.METHOD_SECURITY_ALARM:
                            mMsgHandler.handlerSecurityAlarmMsg(data);
                            break;
                    }
                }, err -> {
                    LogUtils.d("数据异常-->" + err.getMessage());
                });
    }

    //publish后会执行到这里
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {

    }
}
